/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pa165.dominatingspecies.rest;

import com.owlike.genson.ext.jersey.GensonJsonConverter;

import java.util.List;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.filter.HttpBasicAuthFilter;
import pa165.dominating.species.tos.ElementTo;

/**
 *
 * @author Ondrej Prazak, Tomas Kalla, Filip Dinh
 */
public class ElementsPanel extends javax.swing.JPanel {

    private final ClientConfig cfg = new ClientConfig(GensonJsonConverter.class);
    private static final int ID_COLUMN_POSITION = 0;
    private EnumConverter converter = new EnumConverter();
    private static final String restUrl = "http://localhost:8080/pa165/rest";

    /**
     * Creates new form ElementsPanel
     */
    public ElementsPanel() {
        cfg.register(new HttpBasicAuthFilter("rest","rest"));
        initComponents();
        this.setName("Elements");
        initTable();
        updateButton.setEnabled(false);
        outputTextArea.setLineWrap(true);
    }

    private void initTable() {
        elementsTable.setModel(new ElementTableModel());
        elementsTable.setColumnSelectionAllowed(false);
        elementsTable.setRowSelectionAllowed(true);
        elementsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jScrollPane3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        jScrollPane3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        

        elementsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                changeButton.setEnabled(true);
                updateButton.setEnabled(false);
                outputTextArea.setText("");
                descTextArea.setText("");
            }
        });
        getData();
    }

    private void getData() {

        Client client = ClientBuilder.newClient(cfg);
        WebTarget webTarget = client.target(restUrl);
        WebTarget resourceWebTarget = webTarget.path("elements");

        Invocation.Builder invocationBuilder = resourceWebTarget.request(MediaType.APPLICATION_JSON);
        invocationBuilder.header("accept", "application/json");

        int respStat = -1;
        List<ElementTo> lists = null;
        try {
            Response response = invocationBuilder.get();
            respStat = response.getStatus();

            lists = response.readEntity(new GenericType<List<ElementTo>>() {
            });
            for (ElementTo ele : lists) {
                ((ElementTableModel) elementsTable.getModel()).addElementToTable(ele);
            }

        } catch (javax.ws.rs.ProcessingException e) {
            System.out.println("Cannot connect to server.");
            disableButtons();
            outputTextArea.setText("Cannot connect to server!");
        }
        if (respStat == 204) {
            outputTextArea.setText("No data on the server!");
        }
        if (respStat == 200) {
            outputTextArea.setText("Data successfully loaded!");
        }
        if ((respStat != 200) && (respStat != 204)) {
            outputTextArea.setText("Unknown error occured, please restart application.");
        }
        if ((respStat == 200) && (lists != null) && (lists.isEmpty())) {
            outputTextArea.setText("No elements in DB");
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        typeLabel = new javax.swing.JLabel();
        typeComboBox = new javax.swing.JComboBox();
        descLabel = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        descTextArea = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        outputTextArea = new javax.swing.JTextArea();
        outputLabel = new javax.swing.JLabel();
        createButton = new javax.swing.JButton();
        updateButton = new javax.swing.JButton();
        changeButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        elementsTable = new javax.swing.JTable();
        deleteButton = new javax.swing.JButton();
        detailsButton = new javax.swing.JButton();

        typeLabel.setText("Type");

        typeComboBox.setModel(new javax.swing.DefaultComboBoxModel(converter.allEnumsAsStrings()));

        descLabel.setText("Description");

        descTextArea.setColumns(20);
        descTextArea.setRows(5);
        jScrollPane2.setViewportView(descTextArea);

        outputTextArea.setEditable(false);
        outputTextArea.setColumns(20);
        outputTextArea.setRows(5);
        outputTextArea.setFocusable(false);
        outputTextArea.setInheritsPopupMenu(true);
        jScrollPane3.setViewportView(outputTextArea);

        outputLabel.setText("Output");

        createButton.setText("Create");
        createButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createButtonActionPerformed(evt);
            }
        });

        updateButton.setText("Update");
        updateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateButtonActionPerformed(evt);
            }
        });

        changeButton.setText("Change...");
        changeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(createButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE)
                        .addComponent(changeButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(updateButton))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(outputLabel)
                            .addComponent(descLabel)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(typeLabel)
                                .addGap(18, 18, 18)
                                .addComponent(typeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(typeLabel)
                    .addComponent(typeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(15, 15, 15)
                .addComponent(descLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(createButton)
                    .addComponent(changeButton)
                    .addComponent(updateButton))
                .addGap(13, 13, 13)
                .addComponent(outputLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3)
                .addContainerGap())
        );

        elementsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(elementsTable);

        deleteButton.setText("Delete");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        detailsButton.setText("Details");
        detailsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                detailsButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(detailsButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deleteButton)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 449, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(detailsButton)
                    .addComponent(deleteButton))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void createButtonActionPerformed(java.awt.event.ActionEvent evt) {

        Client client = ClientBuilder.newClient(cfg);
        WebTarget webTarget = client.target(restUrl);
        WebTarget resourceWebTarget = webTarget.path("elements/create");

        ElementTo elementTo = new ElementTo();
        elementTo.setDescription(descTextArea.getText());

        elementTo.setType(converter.string2Enum(typeComboBox.getSelectedItem().toString()));

        Invocation.Builder invocationBuilder = resourceWebTarget.request(MediaType.APPLICATION_JSON);
        invocationBuilder.header("accept", "application/json");
        Entity<ElementTo> entity = Entity.json(elementTo);
        Response response = invocationBuilder.post(entity);
        int respStat = response.getStatus();
        System.out.println(respStat);
        if (respStat == 201) {
            descTextArea.setText("");
            typeComboBox.setSelectedIndex(0);
            initTable();
            outputTextArea.setText("Element successfully created!");

        }
        if (respStat == 404) {
            outputTextArea.setText("Element with given type already exists!");
        }

    }

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        int selectedRow = elementsTable.getSelectedRow();
        if (selectedRow < 0) {
            outputTextArea.setText("No element selected!");
            return;
        }
        Client client = ClientBuilder.newClient(cfg);
        WebTarget webTarget = client.target(restUrl);
        WebTarget resourceWebTarget = webTarget.path("elements/delete/" + elementsTable.getModel().getValueAt(elementsTable.getSelectedRow(), ID_COLUMN_POSITION));

        Invocation.Builder invocationBuilder = resourceWebTarget.request(MediaType.APPLICATION_JSON);
        invocationBuilder.header("accept", "application/json");
        
        ElementTo selectedEle = ((ElementTableModel) elementsTable.getModel()).getSelectedElement(selectedRow);

        Response response = invocationBuilder.delete();
        int respStat = response.getStatus();
        if (respStat == 200) {
            ((ElementTableModel) elementsTable.getModel()).deleteElementFromTable(selectedEle);
            outputTextArea.setText("Element successfully deleted!");
        } else {
            outputTextArea.setText("Element cannot be deleted, \nbelongs to environment!");
        }
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateButtonActionPerformed
        Client client = ClientBuilder.newClient(cfg);
        WebTarget webTarget = client.target(restUrl);
        WebTarget resourceWebTarget = webTarget.path("elements/update");

        Invocation.Builder invocationBuilder = resourceWebTarget.request(MediaType.APPLICATION_JSON);
        invocationBuilder.header("accept", "application/json");

        int selectedRow = elementsTable.getSelectedRow();
        ElementTo selectedEle = ((ElementTableModel) elementsTable.getModel()).getSelectedElement(selectedRow);
        
        ElementTo postThisEle = new ElementTo();
        postThisEle.setId(selectedEle.getId());
        postThisEle.setType(converter.string2Enum(typeComboBox.getSelectedItem().toString()));
        postThisEle.setDescription(descTextArea.getText());

        Entity<ElementTo> entity = Entity.json(postThisEle);

        Response response = invocationBuilder.put(entity);
        int respStat = response.getStatus();

        if (respStat == 200) {
            descTextArea.setText("");
            typeComboBox.setSelectedIndex(0);
            outputTextArea.setText("Element successfully updated!");
            selectedEle.setType(postThisEle.getType());
            selectedEle.setDescription(postThisEle.getDescription());
            ((ElementTableModel) elementsTable.getModel()).updateElementInTable(selectedEle);
        }
        if (respStat == 404) {
            outputTextArea.setText(response.readEntity(String.class));
        }
    }//GEN-LAST:event_updateButtonActionPerformed

    private void changeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeButtonActionPerformed
        int selectedRow = elementsTable.getSelectedRow();
        if (selectedRow >= 0) {
            ElementTo selectedEle = ((ElementTableModel) elementsTable.getModel()).getSelectedElement(selectedRow);
            descTextArea.setText(selectedEle.getDescription());
            typeComboBox.setSelectedItem(converter.enum2String(selectedEle.getType()));
            outputTextArea.setText("Change attributes and click 'Update'\nto make changes permanent");
            updateButton.setEnabled(true);
            changeButton.setEnabled(false);
        } else {
            outputTextArea.setText("No element is selected, or given element \ndoes not exist!");
        }
    }//GEN-LAST:event_changeButtonActionPerformed

    private void detailsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_detailsButtonActionPerformed
        int selectedRow = elementsTable.getSelectedRow();
        if (selectedRow < 0) {
            outputTextArea.setText("No element selected!");
            return;
        }
        ElementTo selectedEle = ((ElementTableModel) elementsTable.getModel()).getSelectedElement(selectedRow);
        outputTextArea.setText("Element Details: \nID: " + selectedEle.getId() + "\nType: " + selectedEle.getType() + "\nDescription: "
                + selectedEle.getDescription());
    }//GEN-LAST:event_detailsButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton changeButton;
    private javax.swing.JButton createButton;
    private javax.swing.JButton deleteButton;
    private javax.swing.JLabel descLabel;
    private javax.swing.JTextArea descTextArea;
    private javax.swing.JButton detailsButton;
    private javax.swing.JTable elementsTable;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel outputLabel;
    private javax.swing.JTextArea outputTextArea;
    private javax.swing.JComboBox typeComboBox;
    private javax.swing.JLabel typeLabel;
    private javax.swing.JButton updateButton;
    // End of variables declaration//GEN-END:variables

    private void disableButtons() {
        createButton.setEnabled(false);
        changeButton.setEnabled(false);
        deleteButton.setEnabled(false);
        descTextArea.setEnabled(false);
        detailsButton.setEnabled(false);
        elementsTable.setEnabled(false);
        typeComboBox.setEnabled(false);
        updateButton.setEnabled(false);
    }
}
